"use client";
import { LockOutlined, UserOutlined } from "@ant-design/icons";
import { Button, Card, Col, Form, Input, message, Row } from "antd";
import { getCaptchaApi } from "@/lib/api/system";
import { useRequest } from "ahooks";
import Image from "next/image";
import type { LoginApiParams } from "@/lib/api/system.d";
import { useUserStore } from "@/store/userStore";

export default function Login() {
  const [form] = Form.useForm<LoginApiParams>();
  const userStore = useUserStore();

  const { data: captchaData, run: getCaptcha } = useRequest(getCaptchaApi, {
    onError: (error: any) => {
      message.error(error.msg);
    },
  });

  const { run: login } = useRequest(userStore.login, {
    manual: true,
    onError: (error: any) => {
      message.error(error.msg);
      getCaptcha();
    },
    onSuccess: () => {
      message.success("登录成功");
      window.location.href = "/";
    },
  });

  const onFinish = async () => {
    const res = await form.validateFields();
    if (res) {
      login({
        ...res,
        clientId: process.env.NEXT_PUBLIC_CLIENT_ID,
        grantType: "password",
        tenantId: "000000",
        rememberMe: false,
        uuid: captchaData?.data?.uuid,
      });
    }
  };

  return (
    <Card>
      <p className="text-xl font-bold text-center mb-4">登录</p>
      <Form form={form} onFinish={onFinish} className="mt-4">
        <Form.Item
          name="username"
          rules={[{ required: true, message: "请输入用户名" }]}
        >
          <Input prefix={<UserOutlined />} placeholder="请输入用户名" />
        </Form.Item>
        <Form.Item
          name="password"
          rules={[{ required: true, message: "请输入密码" }]}
        >
          <Input
            prefix={<LockOutlined />}
            type="password"
            placeholder="请输入密码"
          />
        </Form.Item>
        <Row className="w-full">
          <Col span={14}>
            <Form.Item
              name="code"
              rules={[{ required: true, message: "请输入验证码" }]}
            >
              <Input prefix={<LockOutlined />} placeholder="请输入验证码" />
            </Form.Item>
          </Col>
          <Col span={8} offset={2}>
            <Button
              onClick={getCaptcha}
              className="w-[82px] overflow-hidden"
              style={{ padding: 0 }}
            >
              {captchaData?.data?.img ? (
                <Image
                  className="m-0"
                  src={"data:image/gif;base64," + captchaData.data.img}
                  alt="验证码"
                  width={120}
                  height={30}
                />
              ) : (
                "刷新"
              )}
            </Button>
          </Col>
        </Row>
        <Button block type="primary" htmlType="submit">
          登录
        </Button>
      </Form>
    </Card>
  );
}
